import java.net.URL;
import java.util.ArrayList;

public class Page extends ArrayList<String>{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	final static int SEARCH_PAGE = 1;
	final static int DOWN_PAGE = 2;
	
	final static private int ELEMENT_SIZE = 2;
	private String title;
	
	private int mode = 0;
	public Page(int mode){
		super();
		this.mode=mode;
	}
	public URL getbbsLink(){
		if(this.getmode()==SEARCH_PAGE){
			int index = 0;
			index = getindex("bbs_wrap");
			index = getindex("<a href=", "/div", index+1);
			
			this.title=extractTitle(index);
			return extractURL(index);
		}
		else{
			System.out.println("Mode Error");
			return null;
		}
	}
	public int[] getDownEle(){
		if(this.getmode()==DOWN_PAGE){
			int index=0;
			index = getindex("downJm");
			
			return extractEle(index);
		}
		else{
			System.out.println("Mode Error");
			return null;
		}
	}
	private int getindex(String str){
		for(int i=0;i<this.size();i++){
			if(this.get(i).contains(str)) return i;
		}
		if(this.getmode()==1){
			System.out.println("SearchPage : No in Page");
		}
		else if(this.getmode()==2){
			System.out.println("DownPage : No in Page");
		}
		return 0;
	}
	private int getindex(String str, String except, int start){
		for(int i=start;i<this.size();i++){
			if(this.get(i).contains(str)) return i;
			if(this.get(i).contains(except)) break;
		}
		System.out.println("No in Page");
		return 0;
	}
	private String extractTitle(int index){
		String line = this.get(index);
		int start=0, end=0;
		for(int i=0;i<2;i++){
			start = line.indexOf('"',start)+1;
			end = line.indexOf('"',start);
			if(i!=1)start=end+1;
		}
		return line.substring(start, end);
	}
	private URL extractURL(int index){
		String line = this.get(index);
		int start = line.indexOf('"')+1;
		int end = line.indexOf('"',start);
		line = line.substring(start, end);
		
		try{
			return new URL(FileControler.MainURL+line);
		}
		catch(Exception e){
			System.out.println("URL Extract Error");
			return null;
		}
	}
	private int[] extractEle(int index){
		String line = this.get(index);
		int[] element = new int[ELEMENT_SIZE];
		int start=0, end=0;
		try{
			for(int i=0;i<element.length;i++){
				start = line.indexOf("'",start)+1;
				end = line.indexOf("'", start);
				element[i]=Integer.parseInt(line.substring(start, end));
				start = end + 1;
			}
			return element;
		}
		catch(Exception e){
			System.out.println("Extract Element Error");
			return null;
		}
		
	}
	public String getTtitle(){
		return this.title;
	}
	public int getmode(){
		return this.mode;
	}
}
